package site.addzero.cli.autoinit.common

import org.koin.core.annotation.Single
import site.addzero.cli.platform.PlatformTools
import site.addzero.cli.platform.PlatformType
import site.addzero.cli.platform.runCmd
import site.addzero.task.InitTask
import java.io.File
import java.net.URL
import java.nio.channels.Channels
import java.nio.file.Paths

/**
 * FinalShell 自动初始化类
 * 负责下载并安装 FinalShell 远程管理工具
 */
@Single
class AutoInitFinalShell : InitTask {
    override val support: Boolean = true

    /**
     * 执行 FinalShell 初始化任务
     */
    override suspend fun asynctask(): Boolean {
        println("检查 FinalShell 是否已安装...")
        
        if (isFinalShellInstalled()) {
            println("FinalShell 已安装，跳过安装")
            return true
        }

        val installFinalShell = PlatformTools.readBoolWithTrue("是否安装 FinalShell？")
        if (installFinalShell != true) {
            return true
        }

        return downloadAndInstallFinalShell()
    }

    /**
     * 检查 FinalShell 是否已安装
     */
    private fun isFinalShellInstalled(): Boolean {
        return when (PlatformTools.getPlatformType()) {
            PlatformType.WINDOWS -> {
                // 检查 Windows 程序文件目录
                val programFiles = System.getenv("ProgramFiles") ?: "C:\\Program Files"
                val finalShellPath = "$programFiles\\finalshell\\finalshell.exe"
                File(finalShellPath).exists()
            }
            PlatformType.MACOS -> {
                // 检查 Applications 目录
                val finalShellAppPath = "/Applications/FinalShell.app"
                File(finalShellAppPath).exists()
            }
            PlatformType.LINUX -> {
                // 检查常见的 Linux 安装路径
                File("/opt/finalshell/finalshell").exists() || 
                File("/usr/local/finalshell/finalshell").exists()
            }
            else -> false
        }
    }

    /**
     * 下载并安装 FinalShell
     */
    private fun downloadAndInstallFinalShell(): Boolean {
        return try {
            val (downloadUrl, fileName) = getDownloadInfo()
            if (downloadUrl.isEmpty()) {
                println("不支持当前平台或无法获取下载链接")
                return false
            }

            println("开始下载 FinalShell...")
            val tempDir = System.getProperty("java.io.tmpdir")
            val downloadPath = Paths.get(tempDir, fileName).toString()
            
            // 下载文件
            downloadFile(downloadUrl, downloadPath)
            
            println("FinalShell 下载完成，开始安装...")
            installFinalShell(downloadPath)
            
            // 清理下载的文件
            File(downloadPath).delete()
            
            println("FinalShell 安装完成")
            true
        } catch (e: Exception) {
            println("FinalShell 安装失败: ${e.message}")
            false
        }
    }

    /**
     * 根据平台获取下载信息
     */
    private fun getDownloadInfo(): Pair<String, String> {
        val arch = System.getProperty("os.arch").lowercase()
        
        return when (PlatformTools.getPlatformType()) {
            PlatformType.WINDOWS -> {
                "https://dl.hostbuf.com/finalshell3/finalshell_windows_x64.exe" to "finalshell_windows_x64.exe"
            }
            PlatformType.MACOS -> {
                if (arch.contains("aarch64") || arch.contains("arm")) {
                    "https://dl.hostbuf.com/finalshell3/finalshell_macos_arm64.pkg" to "finalshell_macos_arm64.pkg"
                } else {
                    "https://dl.hostbuf.com/finalshell3/finalshell_macos_x64.pkg" to "finalshell_macos_x64.pkg"
                }
            }
            PlatformType.LINUX -> {
                if (arch.contains("aarch64") || arch.contains("arm")) {
                    "https://dl.hostbuf.com/finalshell3/finalshell_linux_arm64.deb" to "finalshell_linux_arm64.deb"
                } else if (arch.contains("loong")) {
                    "https://dl.hostbuf.com/finalshell3/finalshell_linux_loong64.deb" to "finalshell_linux_loong64.deb"
                } else {
                    "https://dl.hostbuf.com/finalshell3/finalshell_linux_x64.deb" to "finalshell_linux_x64.deb"
                }
            }
            else -> "" to ""
        }
    }

    /**
     * 下载文件
     */
    private fun downloadFile(url: String, destination: String) {
        val website = URL(url)
        val rbc = Channels.newChannel(website.openStream())
        val fos = java.io.FileOutputStream(destination)
        fos.channel.transferFrom(rbc, 0, Long.MAX_VALUE)
        fos.close()
        rbc.close()
    }

    /**
     * 安装 FinalShell
     */
    private fun installFinalShell(filePath: String) {
        when (PlatformTools.getPlatformType()) {
            PlatformType.WINDOWS -> {
                // Windows 直接运行安装程序
                val command = "powershell -Command \"Start-Process '$filePath' -Verb RunAs\""
                command.runCmd()
            }
            PlatformType.MACOS -> {
                // macOS 打开 pkg 安装包
                val command = "open '$filePath'"
                command.runCmd()
            }
            PlatformType.LINUX -> {
                // Linux 根据发行版使用相应的包管理器安装
                if (File("/usr/bin/apt").exists()) {
                    // Debian/Ubuntu
                    val command = "sudo dpkg -i '$filePath'"
                    command.runCmd()
                } else if (File("/usr/bin/rpm").exists() || File("/usr/bin/dnf").exists()) {
                    // Fedora/RHEL/CentOS
                    val command = "sudo rpm -i '$filePath'"
                    command.runCmd()
                } else {
                    println("无法识别的 Linux 发行版包管理器，请手动安装: $filePath")
                }
            }
            else -> {
                println("不支持的平台")
            }
        }
    }
}